package com.dhp.mq;

import cn.hutool.core.util.StrUtil;
import com.dhp.Utils.WebSocketUtil;
import com.dhp.constant.MQConstant;
import com.dhp.model.entity.Chart;
import com.dhp.model.enums.GenChartStatusEnum;
import com.dhp.service.ChartService;
import com.dhp.service.UserService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class DeadMessageConsumer {


    @Autowired
    private ChartService chartService;


    @Autowired
    private UserService userService;

    @Autowired
    private WebSocketUtil webSocketUtil;


    /**
     * 死信消费者，将生成失败的图标状态改为failed
     * @param message
     * @param channel
     * @param deliveryTag
     */
    @RabbitListener(queues = {MQConstant.DEAD_QUEUE_NAME} , ackMode = "MANUAL")
    public void receiveMessage(String message , Channel channel , @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){

        if (StrUtil.isEmpty(message)){
            //message为空则拒绝消息
            try {
                channel.basicAck(deliveryTag , false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //如果有异常则自动确认丢弃消息
        try {
            Long charId = Long.parseLong(message);
            Chart errorChart = chartService.getById(charId);
            errorChart.setStatus(GenChartStatusEnum.FAILED.getValue());
            chartService.updateById(errorChart);
            webSocketUtil.sendOneMessage(errorChart.getUserId().toString() , "系统繁忙，请稍后再试");
        }catch (Exception e){
            try {
                channel.basicAck(deliveryTag , false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        try {
            channel.basicAck(deliveryTag , false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
